package com.mt.restaurant.service.material.impl;

import com.mt.restaurant.dao.material.StockRecordDao;

import com.mt.common.core.exception.BusinessException;
import com.mt.common.core.web.base.PageDTO;
import com.mt.common.core.web.base.PageResultDTO;
import com.mt.common.core.web.base.BaseEntity;
import com.mt.common.core.web.BaseService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mt.restaurant.entity.material.StockRecord;
import com.mt.restaurant.service.material.StockRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional
public class StockRecordServiceBean extends BaseService implements StockRecordService {

    private static Logger logger = LogManager.getLogger();

	@Autowired
	private StockRecordDao stockRecordDao;

	@Resource
	private RedisTemplate<String, List<StockRecord>> redisTemplate;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	/**
	 * 根据分页参数查询库存记录集合
	 *
	 * @param pageDTO 分页条件
	 */
	@Override
	public PageResultDTO findStockRecords(PageDTO pageDTO){
        pageDTO.setStartIndex((pageDTO.getCurrentPage()-1)*pageDTO.getPageSize());
		//TODO:请在此校验参数的合法性
		this.validateFindStockRecords(pageDTO);
		List<StockRecord> stockRecordDTOS = this.stockRecordDao.findStockRecords(pageDTO);
		Long totalCount = this.stockRecordDao.findStockRecordTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(stockRecordDTOS);

		return pageResultDTO;
	}

	/**
	 * 查询全部库存记录集合
	 *
	 */
	@Override
	public List<StockRecord> findAllStockRecords(){
		return this.stockRecordDao.findAllStockRecords();
	}

	/**
	 * 查询所有库存记录集合(只提取ID 和 Name)
	 *
	 */
	@Override
	public List<StockRecord> findAllStockRecordsWithIdName(){
		//TODO:请在此校验参数的合法性
		this.validateFindAllStockRecordsWithIdName();
		return this.stockRecordDao.findAllStockRecordsWithIdName();
	}

	/**
	 * 根据名称查询库存记录集合(只提取ID 和 Name)
	 *
	 * @param stockRecordName 名称
	 */
	@Override
	public List<StockRecord> findStockRecordsWithIdNameByName(String stockRecordName){
		//TODO:请在此校验参数的合法性
		this.validateFindStockRecordsWithIdNameByName(stockRecordName);
		//TODO:缓存取对应参数
		Set<String> keys = stringRedisTemplate.keys("searchData:StockRecord_where_stockRecordName_" + stockRecordName);
		List<StockRecord> stockRecords = new ArrayList<>();
		if (keys.isEmpty()) {
		stockRecords = this.stockRecordDao.findStockRecordsWithIdNameByName(stockRecordName);
		redisTemplate.opsForValue().set("searchData:StockRecord_where_stockRecordName_" + stockRecordName, stockRecords, 30, TimeUnit.DAYS);
		} else {
		stockRecords = redisTemplate.opsForValue().get("searchData:StockRecord_where_stockRecordName_" + stockRecordName);
		}
		return stockRecords;
	}

	/**
	 * 根据ID查询指定的库存记录(只提取ID 和 Name)
	 *
	 * @param stockRecordId Id
	 */
	@Override
	public StockRecord findStockRecordsWithIdNameById(Long stockRecordId){
		//TODO:请在此校验参数的合法性
		this.validateFindStockRecordsWithIdNameById(stockRecordId);
		return this.stockRecordDao.findStockRecordsWithIdNameById(stockRecordId);
	}

	/**
	 * 根据ID查询指定的库存记录
	 *
	 * @param stockRecordId Id
	 */
	@Override
	public StockRecord findStockRecord(Long stockRecordId){
		//TODO:请在此校验参数的合法性
		this.validateFindStockRecord(stockRecordId);
		return this.stockRecordDao.findStockRecord(stockRecordId);
	}

	/**
	 * 根据ID查询指定的库存记录(包含外键)
	 *
	 * @param stockRecordId Id
	 */
	@Override
	public StockRecord findStockRecordWithForeignName(Long stockRecordId){
		//TODO:请在此校验参数的合法性
		this.validateFindStockRecordWithForeignName(stockRecordId);
		return this.stockRecordDao.findStockRecordWithForeignName(stockRecordId);
	}

	/**
	 * 新增库存记录
	 *
	 * @param stockRecord 实体对象
	 */
	@Override
	public StockRecord saveStockRecord(StockRecord stockRecord){
		//TODO:请在此校验参数的合法性
		this.validateSaveStockRecord(stockRecord);
		//TODO:填充公共参数
		this.setSavePulicColumns(stockRecord);
		Long rows = this.stockRecordDao.saveStockRecord(stockRecord);
		if(rows != 1)
		{
			String error = "新增保存库存记录出错，数据库应该返回1,但返回了 "+rows;
			throw new BusinessException(error);
		}
		return stockRecord;
	}

	/**
	 * 更新库存记录
	 *
	 * @param stockRecord 实体对象
	 */
	@Override
	public StockRecord updateStockRecord(StockRecord stockRecord){
		//TODO:请在此校验参数的合法性
		this.validateUpdateStockRecord(stockRecord);
		Long rows = this.stockRecordDao.updateStockRecord(stockRecord);
		if(rows != 1)
		{
			String error = "修改保存库存记录出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}
		return stockRecord;
	}

	/**
	 * 根据ID删除库存记录
	 *
	 * @param stockRecordId ID
	 */
	@Override
	public void deleteStockRecord(Long stockRecordId){
		//TODO:请在此校验参数的合法性
		this.validateDeleteStockRecord(stockRecordId);

		Map<Class<? extends BaseEntity>,EntityUsage> entityUsageMap = this.checkForeignEntity(StockRecord.class, stockRecordId);
		if(entityUsageMap != null && entityUsageMap.size() >0){
			StringBuilder errors = new StringBuilder();
			errors.append("计划删除的数据正在被以下数引用\n");
			for(EntityUsage entityUsage : entityUsageMap.values()){
				errors.append("\t").append(entityUsage.getEntityLabel()).append("\n");
				for(Map.Entry<Long,String> entry : entityUsage.getUsageIdNames().entrySet() ){
					errors.append("\t\t").append(entry.getKey()).append("\t").append(entry.getValue()).append("\n");
				}
			}
			errors.append("，不能删除，请检查处理后再删除");
			throw  new BusinessException(errors.toString());
		}

		Long rows = this.stockRecordDao.deleteStockRecord(stockRecordId);
		if(rows != 1){
			String error = "删除库存记录出错，数据可能已经被删除";
			throw new BusinessException(error);
		}
	}

	//TODO:---------------验证-------------------

	private void validateFindStockRecords(PageDTO pageDTO) {
	//TODO:请使用下面方法添加数据过滤条件
	//		pageDTO.addFilter("creatorId",this.getLoginUserId());
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStockRecord()写法
	}

	private void validateFindStockRecordsWithIdNameByName(String stockRecordName) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStockRecord()写法
	}


	private void validateFindAllStockRecordsWithIdName() {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStockRecord()写法
	}

	private void validateFindStockRecordsWithIdNameById(Long stockRecordId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStockRecord()写法
	}

	private void validateFindStockRecord(Long stockRecordId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStockRecord()写法
	}

	private void validateFindStockRecordWithForeignName(Long stockRecordId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStockRecord()写法
	}

	private void validateSaveStockRecord(StockRecord stockRecord) {
	//不为空判断
	if (stockRecord.getEid() != null || stockRecord.getCreatorId() != null || stockRecord.getCreateDatetime() != null) {
	throw new BusinessException("非法请求");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStockRecord()写法
	}

	private void validateUpdateStockRecord(StockRecord stockRecord) {
	//不为空判断
	if (stockRecord.getEid() == null) {
	throw new BusinessException("唯一标识不能为空");
	}
	//是否存在判断
	if (this.stockRecordDao.findStockRecordTotalCount(PageDTO.create(StockRecord.FIELD_ID, stockRecord.getEid())) == 0) {
	throw new BusinessException("修改的库存记录 " + stockRecord.getName() + " 不存在，修改失败，请重试或联系管理员");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStockRecord()写法
	}

	private void validateDeleteStockRecord(Long stockRecordId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateStockRecord()写法
	}

	@Override
	public boolean canDownloadAttachment(String formName, Long id) {
	return true;
	}
}
